package com.chenjj.java.thread.waitnotify;

import java.util.concurrent.atomic.AtomicInteger;

public class Consumer implements Runnable {
    private Object lock;

    private volatile AtomicInteger product;

    private Consumer(){}

    public Consumer(AtomicInteger product,Object lock){
        this.product = product;
        this.lock = lock;
    }


    public void procude() throws InterruptedException {
        while (true){
            synchronized (lock){
                if(product.get() < 0){
                    System.out.println("产品存货不够，等待生产...");
                    lock.wait();
                }else {
                    Thread.sleep(500);
                    product.decrementAndGet();
                    System.out.println("第"+product.get()+"个产品消费完毕");
                    lock.notifyAll();;
                }
            }
        }

    }

    @Override
    public void run() {
        try {
            procude();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
